import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:screenshot/screenshot.dart';
import 'package:yysk_app/model/tab_model.dart';
import 'package:yysk_app/model/user_friend/recommend_user_info_model.dart';
import 'package:yysk_app/pages/nft_pages/my_friend/my_friend_controller.dart';
import 'package:yysk_app/pages/nft_pages/my_friend/my_friend_reward_page.dart';
import 'package:yysk_app/pages/nft_pages/search/search_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/app_bar_back_widget.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/refresh_and_scroll_widget.dart';
import 'package:yysk_app/widget/search_input_widget.dart';
import 'package:yysk_app/widget/tab_widget.dart';

class MyFriendPage extends GetView<MyFriendPageController> {
  static const path = '/MyFriendPage';
  MyFriendPage({super.key});
  final TextEditingController _searchController = TextEditingController();
  GlobalController globalController = Get.find();

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    final userInfo = globalController.user.value;
    return Scaffold(
      backgroundColor: AppColors.backgroundColorBlack,
      bottomNavigationBar: BottomAppBar(
        color: AppColors.backgroundColorBlack,
        padding: EdgeInsets.symmetric(horizontal: 14.px, vertical: 0.px),
        child: ButtonWidget(
          height: 40.px,
          width: 347.px,
          label: '邀请好友',
          fontSize: 15.px,
          fontWeight: FontWeight.w500,
          onPressed: () {
            Future.delayed(const Duration(milliseconds: 1500), () {
              controller.screenshotController.capture().then((img) {
                controller.screenImg.value = img! ?? null;
              });
            });
            showConfirmDialog(
              showBgColor: false,
              context: context,
              closeButton: true,
              children: [
                Screenshot(
                  controller: controller.screenshotController,
                  child: Stack(
                    children: [
                      ImageAssetWidget(
                        imageUrl: 'static/images/invite/invite_bg.png',
                        width: 281.px,
                        height: 315.px,
                        fit: BoxFit.contain,
                      ),
                      Positioned(
                        left: 0.px,
                        right: 0.px,
                        top: 121.px,
                        child: Center(
                          child: QrImageView(
                            data:
                                '${controller.env.envInvitedBaseUrl}?inviteCode=${userInfo?.inviteCode}&head=${Uri.encodeComponent('${userInfo?.avatarImg}')}',
                            version: QrVersions.auto,
                            size: 145.px,
                            gapless: false,
                            // padding: EdgeInsets.all(20.px),
                          ),
                        ),
                      ),
                      Positioned(
                        right: 16.px,
                        bottom: 12.px,
                        child: Row(
                          children: [
                            Container(
                              constraints: BoxConstraints(minWidth: 130.px),
                              decoration: BoxDecoration(
                                color: AppColors.backgroundColor00,
                                borderRadius: BorderRadius.all(
                                  Radius.circular(16.px),
                                ),
                              ),
                              padding: EdgeInsets.fromLTRB(
                                8.px,
                                4.px,
                                8.px,
                                4.px,
                              ),
                              child: Text(
                                '我的邀请码',
                                style: TextStyle(
                                  fontSize: 10.px,
                                  color: AppColors.fontColor,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Positioned(
                        right: 18.px,
                        bottom: 14.px,
                        child: Row(
                          children: [
                            Container(
                              constraints: BoxConstraints(minWidth: 54.px),
                              decoration: BoxDecoration(
                                color: AppColors.backgroundColor,
                                borderRadius: BorderRadius.all(
                                  Radius.circular(16.px),
                                ),
                              ),
                              padding: EdgeInsets.fromLTRB(
                                8.px,
                                2.px,
                                8.px,
                                2.px,
                              ),
                              child: Center(
                                child: Text(
                                  '${userInfo?.inviteCode}',
                                  style: TextStyle(
                                    fontSize: 10.px,
                                    color: AppColors.backgroundColor00,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
              actions: [
                ActionModel(
                  label: '保存图片',
                  colorStart: AppColors.backgroundColorGreyF8,
                  colorEnd: AppColors.backgroundColorGreyF8,
                  fontColor: AppColors.fontColor,
                  onPressed: () async {
                    controller.saveScreenshot(
                      imgBytes: controller.screenImg.value,
                    );
                  },
                ),
                ActionModel(
                  label: '复制链接',
                  onPressed: () {
                    Clipboard.setData(
                      ClipboardData(
                        text:
                            '${controller.env.envInvitedBaseUrl}?inviteCode=${userInfo?.inviteCode}&head=${Uri.encodeComponent('${userInfo?.avatarImg}')}', //userInfo.avatarImg
                      ),
                    );
                    showToast('复制成功');
                  },
                ),
              ],
            );
          },
        ),
      ),
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),

          Obx(() {
            return Container(
              padding: EdgeInsets.fromLTRB(0, top, 0, 0),
              child: Column(
                children: [
                  // SizedBox(height: top),
                  Container(
                    height: preferredSize.height,
                    child: Stack(
                      children: [
                        Positioned(
                          left: 0,
                          right: 0,
                          top: 0,
                          bottom: 0,
                          child: Center(
                            child: Text(
                              controller.labelName.value,
                              style: TextStyle(
                                fontSize: 18.px,
                                color: AppColors.fontColor,
                              ),
                            ),
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            AppBarBackWidget(
                              context: context,
                              onBack: () {},
                              backgroundColor: AppColors.backgroundColor,
                              marginLeft: 7,
                            ),

                            GestureDetector(
                              onTap: () {
                                controller.getMyInvitedInfo().then(
                                  (res) => {
                                    if (res?.successful)
                                      {
                                        myInvitedInfo(
                                          context: context,
                                          detail: res.data,
                                        ),
                                      },
                                  },
                                );
                              },
                              child: Padding(
                                padding: EdgeInsets.only(right: 14.px),
                                child: Row(
                                  children: [
                                    Text(
                                      '我的邀请人',
                                      style: TextStyle(
                                        fontSize: 12.px,
                                        color: AppColors.fontColorGray99,
                                      ),
                                    ),
                                    hiSpace(width: 2.px),
                                    ImageAssetWidget(
                                      imageUrl: 'static/images/right_ico.png',
                                      height: 14.px,
                                      width: 14.px,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  // hiSpace(height: 15.px),
                  GestureDetector(
                    onTap: () {
                      Get.toNamed(SearchPage.path);
                    },
                    child: Container(
                      padding: EdgeInsets.only(left: 14.px, right: 14.px),
                      child: Center(
                        child: SearchInputWidget(
                          hint: '请输入关键词',
                          controller: _searchController,
                          showClose: controller.showClose.value,
                          disabled: true,
                          onChanged: (value) {},
                          onSearch: (value) {},
                          top: top,
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(
                            12.px,
                            18.px,
                            12.px,
                            0.px,
                          ),
                          child: TabWidget(
                            isCurrentFontSize: 15,
                            notCurrentFontSize: 15,
                            tabColor: AppColors.fontColorGray99,
                            value: controller.level.value,
                            tabList: [
                              TabModel(
                                label: '亲密好友',
                                code: '1',
                                bySelf: true,
                                child: _tabChildrenWidget(txt: '亲密好友'),
                              ),
                              TabModel(
                                label: '扩列好友',
                                code: '2',
                                bySelf: true,
                                child: _tabChildrenWidget(txt: '扩列好友'),
                              ),
                            ],
                            onChanged: (val) {
                              controller.changeTab(val);
                            },
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 12.px, right: 12.px),
                          child: Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10.px),
                              border: Border.all(
                                color: AppColors.backgroundColorBlackLight,
                              ),
                              color: AppColors.backgroundColorBlackLight,
                            ),
                            padding: EdgeInsets.fromLTRB(
                              16.px,
                              14.px,
                              16.px,
                              14..px,
                            ),
                            margin: EdgeInsets.only(bottom: 14.px),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                SizedBox(
                                  width: 140.px,
                                  child: Text(
                                    '好友人数：${controller.total.value ?? 0}',
                                    style: TextStyle(
                                      color: AppColors.fontColorGray99,
                                      fontSize: 12.px,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    textAlign: TextAlign.left,
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    Get.toNamed(
                                      '${MyFriendRewardPage.path}?level=${controller.level.value}',
                                      arguments: {
                                        'level': controller.level.value,
                                      },
                                    );
                                  },
                                  child: Row(
                                    children: [
                                      SizedBox(
                                        width: 150.px,
                                        child: Text(
                                          '好友奖励：${controller.totalReward.value}',
                                          style: TextStyle(
                                            color: AppColors.fontColorGray99,
                                            fontSize: 12.px,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          textAlign: TextAlign.left,
                                        ),
                                      ),
                                      hiSpace(width: 2.px),
                                      ImageAssetWidget(
                                        imageUrl: 'static/images/right_ico.png',
                                        height: 14.px,
                                        width: 14.px,
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),

                        Expanded(
                          child: Container(
                            padding: EdgeInsets.fromLTRB(
                              12.px,
                              0.px,
                              12.px,
                              0.px,
                            ),
                            child: RefreshAndScrollWidget(
                              onRefresh: _handleRefresh,
                              scrollController: controller.scrollController,
                              itemBuilder: (item, index) => _itemWidget(item),
                              itemCount: controller.friendList.length,
                              items: controller.friendList,
                              emptyText: '暂无数据~',
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }

  myInvitedInfo({
    required BuildContext context,
    required RecommendUserInfoModel detail,
  }) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: AppColors.backgroundColorBlackLight,
          child: Padding(
            padding: EdgeInsets.fromLTRB(22.px, 22.px, 22.px, 16.px),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '我的邀请人',
                  style: TextStyle(color: AppColors.fontColor, fontSize: 15.px),
                ),
                hiSpace(height: 10.px),
                Text(
                  '受邀时间：${detail.createTime}',
                  style: TextStyle(
                    color: AppColors.fontColorGray99,
                    fontSize: 13.px,
                  ),
                ),
                hiSpace(height: 13.px),
                Container(
                  padding: EdgeInsets.all(11.px),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(11.px),
                    color: AppColors.backgroundColorGreyF8,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      LazyImage(
                        imageUrl: '${detail.avatarImg}',
                        width: 25.px,
                        height: 25.px,
                        boxFit: BoxFit.cover,
                        borderRadius: 25.px,
                      ),
                      hiSpace(width: 11.px),
                      SizedBox(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              width: 180.px,
                              child: RichText(
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                text: TextSpan(
                                  children: <TextSpan>[
                                    TextSpan(
                                      text: '${detail.nickName}',
                                      style: TextStyle(
                                        color: AppColors.fontColor,
                                        fontSize: 15.px,
                                      ),
                                    ),
                                    TextSpan(
                                      text:
                                          ' (${detail.userTel?.substring(detail.userTel!.length - 4)})',
                                      style: TextStyle(
                                        color: AppColors.fontColorGray99,
                                        fontSize: 15.px,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            hiSpace(width: 11.px),
                            Row(
                              children: [
                                SizedBox(
                                  width: 180.px,
                                  child: Text(
                                    'ID：${detail.showId}',
                                    style: TextStyle(
                                      color: AppColors.fontColorGray99,
                                      fontSize: 13.px,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    textAlign: TextAlign.left,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                hiSpace(height: 21.px),
                ButtonWidget(
                  label: '确定',
                  height: 36.px,
                  width: 264.px,
                  fontSize: 15.px,
                  fontColor: AppColors.fontColor21,
                  colorStart: AppColors.fontColorStart00,
                  colorEnd: AppColors.fontColorEnd00,
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                hiSpace(height: 8.px),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _handleRefresh() async {
    controller.getFriendListPage();
    return;
  }

  _itemWidget(item) {
    return Container(
      padding: EdgeInsets.all(10.px),
      margin: EdgeInsets.only(bottom: 8.px),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.px),
        border: Border.all(color: AppColors.backgroundColor.withOpacity(0.1)),
        color: AppColors.backgroundColorBlackLight,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LazyImage(
            imageUrl: item?.avatarImg ?? '',
            width: 24.px,
            height: 24.px,
            boxFit: BoxFit.cover,
            borderRadius: 24.px,
          ),
          hiSpace(width: 10.px),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        width: 140.px,
                        child: RichText(
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          text: TextSpan(
                            children: <TextSpan>[
                              TextSpan(
                                text: '${item.nickName}',
                                style: TextStyle(
                                  color: AppColors.fontColor,
                                  fontSize: 12.px,
                                ),
                              ),
                              TextSpan(
                                text:
                                    ' (${item.userTel.substring(item.userTel.length - 4)})',
                                style: TextStyle(
                                  color: AppColors.fontColorGray99,
                                  fontSize: 12.px,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      hiSpace(height: 10.px),
                      Row(
                        children: [
                          Container(
                            constraints: BoxConstraints(maxWidth: 100.px),
                            child: Text(
                              'ID：${item.showId}',
                              style: TextStyle(
                                color: AppColors.fontColorGray99,
                                fontSize: 12.px,
                                overflow: TextOverflow.ellipsis,
                              ),
                              textAlign: TextAlign.left,
                            ),
                          ),
                          hiSpace(width: 6.px),
                          Container(
                            width: 44.px,
                            height: 18.px,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(2.px),
                              gradient: LinearGradient(
                                begin: Alignment.centerLeft,
                                end: Alignment.centerRight,
                                colors: [
                                  item.isSm
                                      ? AppColors.fontColorStart00
                                      : AppColors.backgroundColorGreyF8,
                                  item.isSm
                                      ? AppColors.fontColorEnd00
                                      : AppColors.backgroundColorGreyF8,
                                ],
                              ),
                            ),
                            child: Center(
                              child: Text(
                                item.isSm ? '已实名' : '未实名',
                                style: TextStyle(
                                  fontSize: 12.px,
                                  color:
                                      item.isSm
                                          ? AppColors.fontColorBlack12
                                          : AppColors.fontColor,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    SizedBox(
                      width: 100.px,
                      child: Text(
                        '${item.rewardAmount}',
                        style: TextStyle(
                          color: AppColors.fontColor,
                          fontSize: 14.px,
                          overflow: TextOverflow.ellipsis,
                        ),
                        textAlign: TextAlign.right,
                      ),
                    ),
                    hiSpace(height: 10.px),

                    Text(
                      '${item.createTime}',
                      style: TextStyle(
                        color: AppColors.fontColorGray99,
                        fontSize: 12.px,
                        overflow: TextOverflow.ellipsis,
                      ),
                      textAlign: TextAlign.right,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _tabChildrenWidget({required String txt}) {
    return Container(
      constraints: BoxConstraints(minWidth: 72.px),
      height: 28.px,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            txt,
            style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 15.px,
              color: AppColors.fontColorSearch, // 注意：这里颜色必须是不透明的，否则会被覆盖
            ),
          ),
          Container(
            width: 16.px,
            height: 2.px,
            color: AppColors.fontColorSearch,
          ),
        ],
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
